﻿using System.Linq.Expressions;
using Model.Entity;

namespace DAL
{
    public class BaseService<T> where T : BaseEntity, new()
    {
        public virtual async Task<int> InsertAsync(T mode)
        {
            var res = DB.SqlSugarClient.Insertable<T>(mode);
            var rows = await res.ExecuteCommandAsync();
            return rows;
        }

        public virtual async Task<bool> UpdateAsync(T mode)
        {
            SqlSugar.IUpdateable<T> updateable = DB.SqlSugarClient.Updateable<T>(mode);
            var rows = await updateable.ExecuteCommandAsync();
            return rows > 0;
        }

        public virtual async Task<bool> DeleteAsync(T mode)
        {
            var res = DB.SqlSugarClient.Deleteable<T>(mode);
            var rows = await res.ExecuteCommandAsync();
            return rows > 0;
        }

        public virtual async Task<T> GetByOneAsync(Expression<Func<T, bool>> where)
        {
            var res = DB.SqlSugarClient.Queryable<T>().Where(where);
            return await res.FirstAsync();
        }

        public virtual async Task<List<T>> GetListAsync(Expression<Func<T, bool>> where)
        {
            var res = DB.SqlSugarClient.Queryable<T>().Where(where);
            return await res.ToListAsync();
        }

        public virtual async Task<bool> ExistASync(Expression<Func<T, bool>> where)
        {
            return await DB.SqlSugarClient.Queryable<T>()
                .Where(where)
                .AnyAsync();
        }
    }
}
